package com.css.fxfzypg.modules.earthquakedisasterloss.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.common.utils.UpdateUtil;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.SettingSeismic.entity.SeismicIntensityRelation;
import com.css.fxfzypg.modules.SettingSeismic.repository.IntensityRelationRepository;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.TrafficAnalysis;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.YpgJcClimate;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.YpgResultSlope;
import com.css.fxfzypg.modules.earthquakedisasterloss.repository.CountLandslideRepository;
import com.css.fxfzypg.modules.earthquakedisasterloss.service.CountLandslideService;
import com.css.fxfzypg.modules.hypergraph.service.HypergraphService;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.qhmapfiles.repository.entity.QhMapFilesEntity;
import com.css.fxfzypg.modules.qhmapfiles.service.QhMapFilesService;
import com.css.fxfzypg.modules.qhmapfiles.viewobjects.QhMapFilesQueryParams;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: fxfzypg
 * @Author: lhl
 * @CreateDate: 2022/10/31 10:16
 */
@Service
public class CountLandslideServiceImpl implements CountLandslideService {

    @Resource
    IntensityRelationRepository intensityRelationRepository;
    @Resource
    CountLandslideRepository countLandslideRepository;
    @Resource
    PreAssessTaskService preAssessTaskService;
    @Resource
    SUserService sUserService;
    @Resource
    SetEarthquakeMapService setEarthquakeMapService;
    @Resource
    QhMapFilesService qhMapFilesService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    SysAreaService sysAreaService;

//    @Resource
//    RestTemplate restTemplate;
    RestTemplate restTemplate = getRestTemplate();
    @Value("${basicData.url1}")
    public String basicDataUrl1;
    @Value("${basicData.url2}")
    public String basicDataUrl2;

    @Resource
    HypergraphService hypergraphService;
    @Resource
    JdbcTemplate jdbcTemplate;

    /**
     * 调度器使用的RestTemplate，超时6000s
     * @return
     */
    public RestTemplate getRestTemplate(){
        RestTemplate restTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofSeconds(6000))
                .setReadTimeout(Duration.ofSeconds(6000))
                .build();
        //解决中文乱码
        List<HttpMessageConverter<?>> msgConv = restTemplate.getMessageConverters();
        if(msgConv != null && !msgConv.isEmpty()) {
            for(int i = 0; i < msgConv.size(); i++ ){
                if(msgConv.get(i).getClass().equals(StringHttpMessageConverter.class)) {
                    msgConv.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
                }
            }
        }
        return restTemplate;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse count1(String taskId, String slopeVersion, String dzIntensity, String parameter, String tab) {
        long startTime = System.currentTimeMillis();
        RestResponse restResponse = null;
        PreAssessTaskEntity taskEntity = preAssessTaskService.getById(taskId);
        SeismicIntensityRelation byTaskId = intensityRelationRepository.getByTaskId(taskId);
        try {
            //根据任务ID、模型类型判断是否更换模型则删除全部计算结果
            if(countLandslideRepository.isDeleteAllResultByType(taskId,"1")){
                countLandslideRepository.delYpgResultSlope(taskId,null);//删除全部烈度计算结果
            }else{
                countLandslideRepository.delYpgResultSlope(taskId,dzIntensity);
            }

            if (PlatformObjectUtils.isEmpty(byTaskId)) {
                restResponse = RestResponse.fail(503, "请生成该任务下的地震影响场");
                return restResponse;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("dzIntensity", dzIntensity);
            map.put("taskDistrict", taskEntity.getTaskDistrict());
            map.put("tab", tab);
            map.put("roadRange", parameter);//道路影响半径m
            map.put("taskId",taskId);
            restResponse = getDataBySlopeVersion3(taskEntity.getGeom(), slopeVersion, map);
            if (restResponse.getCode() != 200) {
                return restResponse;
            }
            String fileName = JSON.parseObject(restResponse.getData().toString()).getString("resultLayerName");
            YpgResultSlope ypgResultSlope = new YpgResultSlope();
            ypgResultSlope.setUuid(UUIDGenerator.getUUID());
            ypgResultSlope.setDzIntensity(dzIntensity);
            ypgResultSlope.setRoadRange(new BigDecimal(parameter));
            ypgResultSlope.setTaskId(taskId);
            ypgResultSlope.setResultSource("1");
            ypgResultSlope.setFilePath(fileName);
            ypgResultSlope.setSlopeVersion(slopeVersion);
            ypgResultSlope.setExtends1("最终计算");
            countLandslideRepository.saveYpgResultSlope(ypgResultSlope);
            //保存空间数据
//            countLandslideRepository.saveYpgResultSlopeData(ypgResultSlope);
            JSONObject resultObj = JSON.parseObject(restResponse.getData().toString());
            if(resultObj.containsKey("分级矢量化")){
                String vectorLayerName = JSON.parseObject(restResponse.getData().toString()).getString("分级矢量化");
                YpgResultSlope ypgResultSlope3 = new YpgResultSlope();
                ypgResultSlope3.setUuid(UUIDGenerator.getUUID());
                ypgResultSlope3.setDzIntensity(dzIntensity);
                ypgResultSlope3.setRoadRange(new BigDecimal(parameter));
                ypgResultSlope3.setTaskId(taskId);
                ypgResultSlope3.setResultSource("1");
                ypgResultSlope3.setFilePath(vectorLayerName);
                ypgResultSlope3.setSlopeVersion(slopeVersion);
                ypgResultSlope3.setExtends1("分级矢量化");
                countLandslideRepository.saveYpgResultSlope(ypgResultSlope3);
            }
            if(resultObj.containsKey("缓冲区4级")){
                String bufferLayerName4 = JSON.parseObject(restResponse.getData().toString()).getString("缓冲区4级");
                YpgResultSlope ypgResultSlope4 = new YpgResultSlope();
                ypgResultSlope4.setUuid(UUIDGenerator.getUUID());
                ypgResultSlope4.setDzIntensity(dzIntensity);
                ypgResultSlope4.setRoadRange(new BigDecimal(parameter));
                ypgResultSlope4.setTaskId(taskId);
                ypgResultSlope4.setResultSource("1");
                ypgResultSlope4.setFilePath(bufferLayerName4);
                ypgResultSlope4.setSlopeVersion(slopeVersion);
                ypgResultSlope4.setExtends1("缓冲区4级");
                countLandslideRepository.saveYpgResultSlope(ypgResultSlope4);
            }
            if(resultObj.containsKey("缓冲区5级")){
                String bufferLayerName5 = JSON.parseObject(restResponse.getData().toString()).getString("缓冲区5级");
                YpgResultSlope ypgResultSlope5 = new YpgResultSlope();
                ypgResultSlope5.setUuid(UUIDGenerator.getUUID());
                ypgResultSlope5.setDzIntensity(dzIntensity);
                ypgResultSlope5.setRoadRange(new BigDecimal(parameter));
                ypgResultSlope5.setTaskId(taskId);
                ypgResultSlope5.setResultSource("1");
                ypgResultSlope5.setFilePath(bufferLayerName5);
                ypgResultSlope5.setSlopeVersion(slopeVersion);
                ypgResultSlope5.setExtends1("缓冲区5级");
                countLandslideRepository.saveYpgResultSlope(ypgResultSlope5);
            }

            byTaskId.setModel7Id("1");
            byTaskId.setModel7Type("1");
            byTaskId.setButton7_status1("1");
            intensityRelationRepository.updateSeismicIntensityRelation(byTaskId);
            System.out.println("计算逻辑斯蒂共用时:{}" + (System.currentTimeMillis() - startTime) / 1000 + "s");
            return ResponseCreator.createSuccessResponse(null, "计算成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("计算失败!");
            return restResponse;
        } finally {
            redisTemplate.delete(taskId);
            if (restResponse != null) {
                if (restResponse.getCode() != 200) {
                    //事务手动回滚
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            }
        }
    }

    private RestResponse count3Detail(String resultLayerName, String currTime, Map<String, Object> map) {
        String dzIntensity = (String) map.get("dzIntensity");
        String roadRange = (String) map.get("roadRange");//道路影响半径m
        String taskId = (String) map.get("taskId");
        //ypg矢量过滤查询
        String clipLayerName = "temp_预评估任务_" + currTime;
        String sqlFilter = "id='"+taskId+"'";
        Map<String, Object> map0 = new HashMap<>();
        map0.put("type", "ypgVectorQuery");
        map0.put("layerName", "ypg_preassess_task");
        map0.put("resultLayerName", clipLayerName);
        map0.put("sqlFilter", sqlFilter);
        map0.put("queryType", "fxfzypg");
        RestResponse serverToken0 = hypergraphService.getServerToken(map0);
        if (serverToken0.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }

        //ypg矢量面裁剪栅格
        String pdLayerName = resultLayerName;//坡度栅格数据集名
        resultLayerName = "temp_ypg逻辑斯蒂裁剪坡度_" + currTime;
        Map<String, Object> map1 = new HashMap<>();
        map1.put("type", "ypgClipTif");
        map1.put("layerName", pdLayerName);
        map1.put("clipLayerName", clipLayerName);
        map1.put("resultLayerName", resultLayerName);
        RestResponse serverToken1 = hypergraphService.getServerToken(map1);
        if (serverToken1.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }

        JSONObject jsonObject = new JSONObject();
        String countString = "Con([ypgTifCount." + resultLayerName + "]==-9999,-9999," +
                "Con([ypgTifCount." + resultLayerName + "]<1,1/(1+exp(8.22178-(0.34329*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<3,1/(1+exp(9.27905-(0.63448*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<7,1/(1+exp(11.3983-(0.916239*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<10,1/(1+exp(10.6025-(0.849128*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<15,1/(1+exp(10.3517-(0.852482*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<20,1/(1+exp(10.0078-(0.847624*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<25,1/(1+exp(9.19721-(0.789875*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<30,1/(1+exp(9.68142-(0.852073*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<35,1/(1+exp(9.65106-(0.8847*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<40,1/(1+exp(10.1154-(0.968573*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<45,1/(1+exp(10.1773-(1.012792*" + dzIntensity + ")))," +
                "Con([ypgTifCount." + resultLayerName + "]<50,1/(1+exp(9.89683-(1.007739*" + dzIntensity + ")))," +
                "1/(1+exp(9.80003-(0.989653*" + dzIntensity + "))))))))))))))))";
        //栅格计算ypg
        Map<String, Object> map3 = new HashMap<>();
        map3.put("type", "ypgCountTif-1");
        String resultLayerName3 = "ypg逻辑斯蒂模型_最终计算_" + currTime + "_" + dzIntensity;//结果数据集
        map3.put("layerName", resultLayerName3);
        map3.put("countString", countString);
        RestResponse serverToken = hypergraphService.getServerToken(map3);
        if (serverToken.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        /*//ypg矢量面裁剪栅格
        String resultLayerName3_clip = "ypg逻辑斯蒂裁剪_最终计算_" + currTime + "_" + dzIntensity;//结果数据集
        Map<String, Object> map3_1 = new HashMap<>();
        map3_1.put("type", "ypgClipTif");
        map3_1.put("layerName", resultLayerName3);
        map3_1.put("clipLayerName", clipLayerName);
        map3_1.put("resultLayerName", resultLayerName3_clip);
        RestResponse serverToken_1 = hypergraphService.getServerToken(map3_1);
        if (serverToken_1.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        //ypg计算数据自动制图发布图层模板
        Map<String, Object> map3_2 = new HashMap<>();
        map3_2.put("type", "ypgMapsLayer");
        map3_2.put("layerName", resultLayerName3_clip);
        map3_2.put("mapsName", "指数-逻辑模板-图例.xml");
        RestResponse serverToken_2 = hypergraphService.getServerToken(map3_2);
        if (serverToken_2.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        jsonObject.put("resultLayerName", resultLayerName3_clip);//最终计算*/
        jsonObject.put("resultLayerName", resultLayerName3);//最终计算

        //栅格计算ypg
        String countString1 = "Con([ypgTifCount." + resultLayerName3 + "]==-9999,-9999," +
                "Con([ypgTifCount." + resultLayerName3 + "]<=0.01,1," +
                "Con([ypgTifCount." + resultLayerName3 + "]<=0.03,2," +
                "Con([ypgTifCount." + resultLayerName3 + "]<=0.09,3," +
                "Con([ypgTifCount." + resultLayerName3 + "]<=0.27,4,5)))))";
        Map<String, Object> map5 = new HashMap<>();
        map5.put("type", "ypgCountTif-1");
        map5.put("countString", countString1);
        String resultLayerName3_1 = "ypg逻辑斯蒂模型_分级计算_" + currTime + "_" + dzIntensity;//栅格计算结果数据集
        map5.put("layerName", resultLayerName3_1);
        RestResponse serverToken2 = hypergraphService.getServerToken(map5);
        if (serverToken2.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        jsonObject.put("分级计算", resultLayerName3_1);

        //ypg全部栅格矢量化
        String resultLayerName4_0 = "temp_逻辑斯蒂矢量化_" + currTime + "_" + dzIntensity;
        Map<String, Object> map6 = new HashMap<>();
        map6.put("type", "countTifAllVector");
        map6.put("layerName", resultLayerName3_1);
        map6.put("resultLayerName", resultLayerName4_0);
        RestResponse serverToken3 = hypergraphService.getServerToken(map6);
        if (serverToken3.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        //ypg矢量求交--任务区域内
        String resultLayerName4 = "ypg逻辑斯蒂模型_矢量化_" + currTime + "_" + dzIntensity;
        Map<String, Object> map6_1 = new HashMap<>();
        map6_1.put("type", "ypgIntersects");
        map6_1.put("layerName", resultLayerName4_0);
        map6_1.put("clipLayerName", clipLayerName);
        map6_1.put("resultLayerName", resultLayerName4);
        RestResponse serverToken3_1 = hypergraphService.getServerToken(map6_1);
        if (serverToken3_1.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        //ypg计算数据自动制图发布图层模板
        Map<String, Object> map6_2 = new HashMap<>();
        map6_2.put("type", "ypgMapsLayer");
        map6_2.put("layerName", resultLayerName4);
        map6_2.put("mapsName", "逻辑斯蒂滑坡分级矢量图层模板.xml");
        RestResponse serverToken3_2 = hypergraphService.getServerToken(map6_2);
        if (serverToken3_2.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        jsonObject.put("分级矢量化", resultLayerName4);

        for(int i=4;i<=5;i++){
            String gridvalue = String.valueOf(i);
            //ypg指定栅格矢量化缓冲区
            String resultLayerName5 = "temp_逻辑斯蒂_矢量化"+gridvalue+"_" + currTime + "_" + dzIntensity;
            String resultLayerName6_0 = "temp_逻辑斯蒂_缓冲区"+gridvalue+"_" + currTime + "_" + dzIntensity;
            Map<String, Object> map7 = new HashMap<>();
            map7.put("type", "countTifValueBuffer");
//            map7.put("layerName", resultLayerName3_1);//栅格分级计算
            map7.put("layerName", resultLayerName4);//栅格分级计算矢量化任务区域内
            map7.put("resultLayerName", resultLayerName5);
            map7.put("resultLayerName2", resultLayerName6_0);
            map7.put("gridvalue", gridvalue);
            map7.put("bufferMeter", roadRange);
            RestResponse serverToken4 = hypergraphService.getServerToken(map7);
            if (serverToken4.getCode() == 200) {
                //ypg矢量求交--任务区域内
                String resultLayerName6 = "ypg逻辑斯蒂模型_缓冲区"+gridvalue+"_" + currTime + "_" + dzIntensity;
                Map<String, Object> map7_1 = new HashMap<>();
                map7_1.put("type", "ypgIntersects");
                map7_1.put("layerName", resultLayerName6_0);
                map7_1.put("clipLayerName", clipLayerName);
                map7_1.put("resultLayerName", resultLayerName6);
                RestResponse serverToken4_1 = hypergraphService.getServerToken(map7_1);
                if (serverToken4_1.getCode() == 200) {
                    //ypg计算数据自动制图发布图层模板
                    Map<String, Object> map7_2 = new HashMap<>();
                    map7_2.put("type", "ypgMapsLayer");
                    map7_2.put("layerName", resultLayerName6);
                    map7_2.put("mapsName", "震后交通情况分布图_缓冲区图层模板.xml");
                    RestResponse serverToken4_2 = hypergraphService.getServerToken(map7_2);
                    if (serverToken4_2.getCode() == 200) {
                        //ypgTifCount复制数据集到fxfzypg
                        Map<String, Object> map7_3 = new HashMap<>();
                        map7_3.put("type", "ypgCountCopyVector");
                        map7_3.put("layerName", resultLayerName6);
                        RestResponse serverToken4_3 = hypergraphService.getServerToken(map7_3);
                        if (serverToken4_3.getCode() == 200) {
                            if(i==4){
                                jsonObject.put("缓冲区4级", resultLayerName6);
                            }else if(i==5){
                                jsonObject.put("缓冲区5级", resultLayerName6);
                            }
                        }
                    }
                }
            }
        }

        return RestResponse.succeed(jsonObject);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse count2(String taskId, String dzIntensity, String parameter, String slopeVersion, String lithologyVersion,
                               String phyVersion, String natDenVersion) {
        RestResponse restResponse = null;

        PreAssessTaskEntity taskEntity = preAssessTaskService.getById(taskId);
        SeismicIntensityRelation byTaskId = intensityRelationRepository.getByTaskId(taskId);
        try {
            Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));

            //根据任务ID、模型类型判断是否更换模型则删除全部计算结果
            if(countLandslideRepository.isDeleteAllResultByType(taskId,"2")){
                countLandslideRepository.delYpgResultSlope(taskId,null);//删除全部烈度计算结果
            }else{
                countLandslideRepository.delYpgResultSlope(taskId,dzIntensity);
            }

            if (PlatformObjectUtils.isEmpty(byTaskId)) {
                restResponse = RestResponse.fail(503, "请生成该任务下的地震影响场");
                return restResponse;
            }
            String geom = taskEntity.getGeom();
            // if (PlatformObjectUtils.isNotEmpty(redisTemplate.opsForValue().get(taskId))) {
            //     return RestResponse.fail("该线程中的该数据:{}" + taskEntity.getTaskName() + "正在被计算！");
            // }
            // redisTemplate.opsForValue().set(taskId, "2", 10L, TimeUnit.SECONDS);

            //ypg矢量过滤查询
            String currTime = System.currentTimeMillis() + "";
//            String clipLayerName = "ypg_preassess_task";
            String clipLayerName = "temp_预评估任务_" + currTime;
            String sqlFilter = "id='"+taskId+"'";
            Map<String, Object> map0 = new HashMap<>();
            map0.put("type", "ypgVectorQuery");
            map0.put("layerName", "ypg_preassess_task");
            map0.put("resultLayerName", clipLayerName);
            map0.put("sqlFilter", sqlFilter);
            map0.put("queryType", "fxfzypg");
            RestResponse serverToken0 = hypergraphService.getServerToken(map0);
            if (serverToken0.getCode() != 200) {
                return RestResponse.fail(503, "计算失败！");
            }

            RestResponse serverToken1 = vectorTif("vectorTif-4", "jc_stratum_lithology", clipLayerName,
                    "values1", "data_version='" + lithologyVersion + "' and del_flag='0'"
                    , "task_num='" + taskEntity.getTaskNum() + "' and del_flag='0'",currTime);
            if (serverToken1.getCode() != 200) {
                restResponse = RestResponse.fail(503, "该区域没有" + lithologyVersion + "版本的地层岩性数据");
                return restResponse;
            }
            String resultLayerName1 = JSON.parseObject(JSON.toJSONString(serverToken1.getData()))
                    .getString("resultLayerName");
            System.out.println(lithologyVersion + "版本的地层岩性:{}" + resultLayerName1 + "解析成功！");

            RestResponse serverToken2 = vectorTif("vectorTif-3", "dzzh_sys_landform", clipLayerName,
                    "values1", "data_version='" + phyVersion + "' and del_flag='0'"
                    , "task_num='" + taskEntity.getTaskNum() + "' and del_flag='0'",currTime);
            if (serverToken2.getCode() != 200) {
                restResponse = RestResponse.fail(503, "该区域没有" + phyVersion + "版本的地貌数据");
                return restResponse;
            }
            String resultLayerName2 = JSON.parseObject(JSON.toJSONString(serverToken2.getData()))
                    .getString("resultLayerName");
            System.out.println(phyVersion + "版本的地貌:{}" + resultLayerName2 + "解析成功！");

            //气候---------
            countLandslideRepository.delYpgJcClimate(taskId);
            String url = basicDataUrl1 + "/datacenter/jcClimate/getByArea?1=1";
            for (String s1 : taskEntity.getTaskDistrict().split("、")) {
                if (s1 != null) {
                    String geomText = null;
                    String[] s2 = s1.split("-");
                    String divisionIds = null;
                    try {
                        if (s2.length == 1) {
                            url = url + "&province=" + s2[0] + "&city=&county=";
                            divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(s2[0], "UTF-8"),
                                    null, null);
                        } else if (s2.length == 2 || s2.length == 3) {
                            url = url + "&province=" + s2[0] + "&city=" + s2[1] + "&county=";
                            if (s2.length == 2) {
                                divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(s2[0], "UTF-8"),
                                        URLEncoder.encode(s2[1], "UTF-8"), null);
                            } else if (s2.length == 3) {
                                divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(s2[0], "UTF-8"),
                                        URLEncoder.encode(s2[1], "UTF-8"), URLEncoder.encode(s2[2], "UTF-8"));
                            }
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    if (divisionIds == null) {
                        return null;
                    }
                    String[] split = divisionIds.split("_");
                    if (split.length == 1) {
                        geomText = getGeomByCode(areaIdCodeMap.get(split[0]), "1");
                    } else if (split.length == 2) {
                        geomText = getGeomByCode(areaIdCodeMap.get(split[1]), "2");
                    } else {
                        geomText = getGeomByCode(areaIdCodeMap.get(split[2]), "3");
                    }
                    if (PlatformObjectUtils.isEmpty(geomText)) {
                        return RestResponse.fail("未获取到气候数据的" + s2.toString() + "的空间数据，无法进行计算！");
                    }
                    JSONArray jsonArray = (JSONArray) getJCSJ(url, 3).getData();
                    if (jsonArray == null) {
                        restResponse = RestResponse.fail(503, "该区域没有气候数据");
                        return restResponse;
                    }
                    BigDecimal jyl = BigDecimal.ZERO;
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        jyl = jyl.add(jsonObject.getBigDecimal("avPrec"));
                    }
                    YpgJcClimate ypgJcClimate = new YpgJcClimate();
                    ypgJcClimate.setId(UUIDGenerator.getUUID());
                    ypgJcClimate.setAvPrec(jyl);
                    ypgJcClimate.setGeomText(geomText);
                    ypgJcClimate.setTaskId(taskId);
                    countLandslideRepository.saveYpgJcClimate(ypgJcClimate);
                }
            }
            // 刷新指定超图工作空间数据源数据集
            boolean b2 = hypergraphService.getWorkspaceReload("ypg_jc_climate");

            RestResponse serverToken3 = vectorTif("vectorTif-5", "ypg_jc_climate", clipLayerName,
                    "av_prec", "task_id='" + taskId + "' "
                    , "task_num='" + taskEntity.getTaskNum() + "' and del_flag='0'",currTime);
            if (serverToken3.getCode() != 200) {
                restResponse = RestResponse.fail(503, "该区域没有气候数据");
                return restResponse;
            }
            String resultLayerName3 = JSON.parseObject(JSON.toJSONString(serverToken3.getData()))
                    .getString("resultLayerName");
            System.out.println("气候:{}" + resultLayerName3 + "解析成功！");

            RestResponse serverToken4 = vectorTif("vectorTif-3", "dzzh_sys_natural_density", clipLayerName,
                    "dsn_name", "data_version='" + natDenVersion + "' and del_flag='0'"
                    , "task_num='" + taskEntity.getTaskNum() + "' and del_flag='0'",currTime);
            if (serverToken4.getCode() != 200) {
                restResponse = RestResponse.fail(503, "该区域没有" + natDenVersion + "版本的天然密度数据");
                return restResponse;
            }
            String resultLayerName4 = JSON.parseObject(JSON.toJSONString(serverToken4.getData()))
                    .getString("resultLayerName");
            System.out.println(natDenVersion + "版本的天然密度:{}" + resultLayerName4 + "解析成功！");

            Map<String, Object> map = new HashMap<>();
            map.put("dzIntensity", dzIntensity);
            map.put("resultLayerName1", resultLayerName1);
            map.put("resultLayerName2", resultLayerName2);
            map.put("resultLayerName3", resultLayerName3);
            map.put("resultLayerName4", resultLayerName4);
            map.put("roadRange", parameter);//道路影响半径m
            map.put("taskId",taskId);
            map.put("currTime",currTime);
            map.put("clipLayerName",clipLayerName);
            restResponse = getDataBySlopeVersion4(geom, slopeVersion, map);
            if (restResponse.getCode() != 200) {
                return restResponse;
            }
            String fileName = JSON.parseObject(restResponse.getData().toString()).getString("resultLayerName");
            YpgResultSlope ypgResultSlope = new YpgResultSlope();
            ypgResultSlope.setUuid(UUIDGenerator.getUUID());
            ypgResultSlope.setDzIntensity(dzIntensity);
            ypgResultSlope.setRoadRange(new BigDecimal(parameter));
            ypgResultSlope.setTaskId(taskId);
            ypgResultSlope.setResultSource("2");
            ypgResultSlope.setFilePath(fileName);
            ypgResultSlope.setSlopeVersion(slopeVersion);
            ypgResultSlope.setLithologyVersion(lithologyVersion);
            ypgResultSlope.setPhyVersion(phyVersion);
            ypgResultSlope.setNatDenVersion(natDenVersion);
            ypgResultSlope.setExtends1("最终计算");
            countLandslideRepository.saveYpgResultSlope(ypgResultSlope);
            //保存空间数据
//            countLandslideRepository.saveYpgResultSlopeData(ypgResultSlope);
            JSONObject resultObj = JSON.parseObject(restResponse.getData().toString());
            if(resultObj.containsKey("分级矢量化")){
                String vectorLayerName = JSON.parseObject(restResponse.getData().toString()).getString("分级矢量化");
                YpgResultSlope ypgResultSlope3 = new YpgResultSlope();
                ypgResultSlope3.setUuid(UUIDGenerator.getUUID());
                ypgResultSlope3.setDzIntensity(dzIntensity);
                ypgResultSlope3.setRoadRange(new BigDecimal(parameter));
                ypgResultSlope3.setTaskId(taskId);
                ypgResultSlope3.setResultSource("2");
                ypgResultSlope3.setFilePath(vectorLayerName);
                ypgResultSlope3.setSlopeVersion(slopeVersion);
                ypgResultSlope3.setExtends1("分级矢量化");
                countLandslideRepository.saveYpgResultSlope(ypgResultSlope3);
            }
            if(resultObj.containsKey("缓冲区4级")){
                String bufferLayerName4 = JSON.parseObject(restResponse.getData().toString()).getString("缓冲区4级");
                YpgResultSlope ypgResultSlope4 = new YpgResultSlope();
                ypgResultSlope4.setUuid(UUIDGenerator.getUUID());
                ypgResultSlope4.setDzIntensity(dzIntensity);
                ypgResultSlope4.setRoadRange(new BigDecimal(parameter));
                ypgResultSlope4.setTaskId(taskId);
                ypgResultSlope4.setResultSource("2");
                ypgResultSlope4.setFilePath(bufferLayerName4);
                ypgResultSlope4.setSlopeVersion(slopeVersion);
                ypgResultSlope4.setExtends1("缓冲区4级");
                countLandslideRepository.saveYpgResultSlope(ypgResultSlope4);
            }

            byTaskId.setModel7Id("1");
            byTaskId.setModel7Type("2");
            byTaskId.setButton7_status1("1");
            intensityRelationRepository.updateSeismicIntensityRelation(byTaskId);
            return ResponseCreator.createSuccessResponse(null, "计算成功!");
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("计算失败!");
            return restResponse;
        } finally {
            redisTemplate.delete(taskId);
            // if (restResponse != null) {
            //     if (restResponse.getCode() != 200) {
            //         //事务手动回滚
            //         TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //     }
            // }
        }
    }

    public String getGeomByCode(String code, String flag) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "dzzhfxpgyqhxt");
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(code, headers);
        String url = null;
        if ("1".equals(flag)) {
            url = basicDataUrl1 + "/datacenter/jcBoua2/getGeomByCode";
        } else if ("2".equals(flag)) {
            url = basicDataUrl1 + "/datacenter/jcBoua4/getGeomByCode";
        } else {
            url = basicDataUrl1 + "/datacenter/jcBoua5/getGeomByCode";
        }
        try {
            JSONObject body = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
            if (body == null) {
                return null;
            }
            return (String) body.get("data");
        } catch (RestClientException e) {
            System.out.println("error -> url: {}" + url);
            throw e;
        }
    }


    private RestResponse count4Detail(String resultLayerName1, Map<String, Object> map, String currTime) {
        JSONObject jsonObject = new JSONObject();
        String dzIntensity = (String) map.get("dzIntensity");
        String roadRange = (String) map.get("roadRange");//道路影响半径m
        String clipLayerName = (String) map.get("clipLayerName");//任务区域边界数据集

        String resultLayerName2 = (String) map.get("resultLayerName1");
        String resultLayerName3 = (String) map.get("resultLayerName2");
        String resultLayerName4 = (String) map.get("resultLayerName3");
        String resultLayerName5 = (String) map.get("resultLayerName4");
//        String countString1 = "Con([ypgTifCount." + resultLayerName1 + "]>=30,6,Con([ypgTifCount." + resultLayerName1 + "]>24,5,Con([ypgTifCount." + resultLayerName1 + "]>18,4,Con([ypgTifCount." + resultLayerName1 + "]>12,3,Con([ypgTifCount." + resultLayerName1 + "]>=5,2,Con([ypgTifCount." + resultLayerName1 + "]<5,1,0))))))";
        String countString1 = "Con([ypgTifCount." + resultLayerName1 + "]==-9999,0,Con([ypgTifCount." + resultLayerName1 + "]>=30,6,Con([ypgTifCount." + resultLayerName1 + "]>=24,5,Con([ypgTifCount." + resultLayerName1 + "]>=18,4,Con([ypgTifCount." + resultLayerName1 + "]>=12,3,Con([ypgTifCount." + resultLayerName1 + "]>=5,2,1))))))";
        //栅格计算
        String resultLayerName_1 = "temp_ypg黄土高原模型计算_" + currTime + "_" + 1;//坡度
        RestResponse restResponse1 = countTif("ypgCountTif-1", countString1, resultLayerName_1);
        if (restResponse1.getCode() != 200) {
            restResponse1.setCode(503);
            return restResponse1;
        }
//        String countString2 = "Con([ypgTifCount." + resultLayerName2 + "]>12,1,Con([ypgTifCount." + resultLayerName2 + "]==12,3,Con([ypgTifCount." + resultLayerName2 + "]<12,5,0)))";
        String countString2 = "Con([ypgTifCount." + resultLayerName2 + "]==-9999,0,Con([ypgTifCount." + resultLayerName2 + "]>12,1,Con([ypgTifCount." + resultLayerName2 + "]==12,3,5)))";
        String resultLayerName_2 = "temp_ypg黄土高原模型计算_" + currTime + "_" + 2;//地层时代
        RestResponse restResponse2 = countTif("ypgCountTif-1", countString2, resultLayerName_2);
        if (restResponse2.getCode() != 200) {
            restResponse1.setCode(503);
            return restResponse2;
        }
//        String countString3 = "Con([ypgTifCount." + resultLayerName3 + "]<=3,1,Con([ypgTifCount." + resultLayerName3 + "]<=7,4,0))";
        String countString3 = "Con([ypgTifCount." + resultLayerName3 + "]==-9999,0,Con([ypgTifCount." + resultLayerName3 + "]<=3,1,Con([ypgTifCount." + resultLayerName3 + "]<=7,4,0)))";
        String resultLayerName_3 = "temp_ypg黄土高原模型计算_" + currTime + "_" + 3;//地貌
        RestResponse restResponse3 = countTif("ypgCountTif-1", countString3, resultLayerName_3);
        if (restResponse3.getCode() != 200) {
            restResponse1.setCode(503);
            return restResponse3;
        }
//        String countString4 = "Con([ypgTifCount." + resultLayerName4 + "]>=600,6,Con([ypgTifCount." + resultLayerName4 + "]>500,5,Con([ypgTifCount." + resultLayerName4 + "]>400,4,Con([ypgTifCount." + resultLayerName4 + "]>300,3,Con([ypgTifCount." + resultLayerName4 + "]>=200,2,Con([ypgTifCount." + resultLayerName4 + "]<200,1,0))))))";
        String countString4 = "Con([ypgTifCount." + resultLayerName4 + "]==-9999,0,Con([ypgTifCount." + resultLayerName4 + "]>=600,6,Con([ypgTifCount." + resultLayerName4 + "]>=500,5,Con([ypgTifCount." + resultLayerName4 + "]>=400,4,Con([ypgTifCount." + resultLayerName4 + "]>=300,3,Con([ypgTifCount." + resultLayerName4 + "]>=200,2,1))))))";
        String resultLayerName_4 = "temp_ypg黄土高原模型计算_" + currTime + "_" + 4;//降雨量
        RestResponse restResponse4 = countTif("ypgCountTif-1", countString4, resultLayerName_4);
        if (restResponse4.getCode() != 200) {
            restResponse1.setCode(503);
            return restResponse4;
        }
//        String countString5 = "Con([ypgTifCount." + resultLayerName5 + "]>=1.8,1,Con([ypgTifCount." + resultLayerName5 + "]>1.7,2,Con([ypgTifCount." + resultLayerName5 + "]>1.6,3,Con([ypgTifCount." + resultLayerName5 + "]>1.5,4,Con([ypgTifCount." + resultLayerName5 + "]>=1.4,5,Con([ypgTifCount." + resultLayerName5 + "]<1.4,6,0))))))";
        String countString5 = "Con([ypgTifCount." + resultLayerName5 + "]==-9999,0,Con([ypgTifCount." + resultLayerName5 + "]>=1.8,1,Con([ypgTifCount." + resultLayerName5 + "]>=1.7,2,Con([ypgTifCount." + resultLayerName5 + "]>=1.6,3,Con([ypgTifCount." + resultLayerName5 + "]>=1.5,4,Con([ypgTifCount." + resultLayerName5 + "]>=1.4,5,6))))))";
        String resultLayerName_5 = "temp_ypg黄土高原模型计算_" + currTime + "_" + 5;//天然密度
        RestResponse restResponse5 = countTif("ypgCountTif-1", countString5, resultLayerName_5);
        if (restResponse5.getCode() != 200) {
            restResponse1.setCode(503);
            return restResponse5;
        }
        BigDecimal yz1 = BigDecimal.ZERO;
        switch (dzIntensity) {
            case "6":
                dzIntensity = String.valueOf(6);
                yz1 = BigDecimal.valueOf(1);
            case "7":
                dzIntensity = String.valueOf(7);
                yz1 = BigDecimal.valueOf(2);
                break;
            case "8":
                dzIntensity = String.valueOf(8);
                yz1 = BigDecimal.valueOf(4);
                break;
            case "9":
                dzIntensity = String.valueOf(9);
                yz1 = BigDecimal.valueOf(5);
                break;
            case "10":
                dzIntensity = String.valueOf(10);
                yz1 = BigDecimal.valueOf(6);
                break;
        }
        //栅格计算ypg
//        String countString_6 = "Con([ypgTifCount." + resultLayerName_1 + "]==-9999,0,[ypgTifCount." + resultLayerName_1 + "]*0.1543)" +
//                "+Con([ypgTifCount." + resultLayerName_2 + "]==-9999,0,[ypgTifCount." + resultLayerName_2 + "]*0.0599)" +
//                "+Con([ypgTifCount." + resultLayerName_3 + "]==-9999,0,[ypgTifCount." + resultLayerName_3 + "]*0.2734)" +
//                "+Con([ypgTifCount." + resultLayerName_4 + "]==-9999,0,[ypgTifCount." + resultLayerName_4 + "]*0.0878)" +
//                "+Con([ypgTifCount." + resultLayerName_5 + "]==-9999,0,[ypgTifCount." + resultLayerName_5 + "]*0.0412)" +
//                "+(" + yz1 + "*0.3834)";
        String countString_6 = "[ypgTifCount." + resultLayerName_1 + "]*0.1543" +
                "+[ypgTifCount." + resultLayerName_2 + "]*0.0599" +
                "+[ypgTifCount." + resultLayerName_3 + "]*0.2734" +
                "+[ypgTifCount." + resultLayerName_4 + "]*0.0878" +
                "+[ypgTifCount." + resultLayerName_5 + "]*0.0412" +
                "+(" + yz1 + "*0.3834)";
        Map<String, Object> map2 = new HashMap<>();
        map2.put("type", "ypgCountTif-1");
        String resultLayerName_6 = "ypg黄土高原模型_最终计算_" + currTime + "_" + dzIntensity;//结果数据集
        map2.put("layerName", resultLayerName_6);
        map2.put("countString", countString_6);
        RestResponse restResponse7 = hypergraphService.getServerToken(map2);
        if (restResponse7.getCode() != 200) {
            restResponse1.setCode(503);
            return restResponse7;
        }
        /*//ypg矢量面裁剪栅格
        String resultLayerName6_clip = "ypg黄土高原裁剪_最终计算_" + currTime + "_" + dzIntensity;//结果数据集
        Map<String, Object> map3_1 = new HashMap<>();
        map3_1.put("type", "ypgClipTif");
        map3_1.put("layerName", resultLayerName_6);
        map3_1.put("clipLayerName", clipLayerName);
        map3_1.put("resultLayerName", resultLayerName6_clip);
        RestResponse serverToken_1 = hypergraphService.getServerToken(map3_1);
        if (serverToken_1.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        //ypg计算数据自动制图发布图层模板
        Map<String, Object> map3_2 = new HashMap<>();
        map3_2.put("type", "ypgMapsLayer");
        map3_2.put("layerName", resultLayerName6_clip);
        map3_2.put("mapsName", "黄土模板-图例.xml");
        RestResponse serverToken_2 = hypergraphService.getServerToken(map3_2);
        if (serverToken_2.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        jsonObject.put("resultLayerName", resultLayerName6_clip);//最终计算*/
        jsonObject.put("resultLayerName", resultLayerName_6);//最终计算

        //栅格计算ypg
        String countString6 = "Con([ypgTifCount." + resultLayerName_6 + "]==-9999,-9999," +
                "Con([ypgTifCount." + resultLayerName_6 + "]<2.8,1," +
                "Con([ypgTifCount." + resultLayerName_6 + "]<3.5,2," +
                "Con([ypgTifCount." + resultLayerName_6 + "]<=4.3,3,4))))";
        Map<String, Object> map5 = new HashMap<>();
        map5.put("type", "ypgCountTif-1");
        map5.put("countString", countString6);
        String resultLayerName3_1 = "ypg黄土高原模型_分级计算_" + currTime + "_" + dzIntensity;//栅格计算结果数据集
        map5.put("layerName", resultLayerName3_1);
        RestResponse serverToken2 = hypergraphService.getServerToken(map5);
        if (serverToken2.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        jsonObject.put("分级计算", resultLayerName3_1);

        //ypg全部栅格矢量化
        String resultLayerName_7 = "temp_黄土高原矢量化_" + currTime + "_" + dzIntensity;
        Map<String, Object> map6 = new HashMap<>();
        map6.put("type", "countTifAllVector");
        map6.put("layerName", resultLayerName3_1);
        map6.put("resultLayerName", resultLayerName_7);
        RestResponse serverToken3 = hypergraphService.getServerToken(map6);
        if (serverToken3.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        //ypg矢量求交--任务区域内
        String resultLayerName7 = "ypg黄土高原模型_矢量化_" + currTime + "_" + dzIntensity;
        Map<String, Object> map6_1 = new HashMap<>();
        map6_1.put("type", "ypgIntersects");
        map6_1.put("layerName", resultLayerName_7);
        map6_1.put("clipLayerName", clipLayerName);
        map6_1.put("resultLayerName", resultLayerName7);
        RestResponse serverToken3_1 = hypergraphService.getServerToken(map6_1);
        if (serverToken3_1.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        //ypg计算数据自动制图发布图层模板
        Map<String, Object> map6_2 = new HashMap<>();
        map6_2.put("type", "ypgMapsLayer");
        map6_2.put("layerName", resultLayerName7);//ypg矢量求交--任务区域内
        map6_2.put("mapsName", "黄土高原滑坡分级矢量图层模板.xml");
        RestResponse serverToken3_2 = hypergraphService.getServerToken(map6_2);
        if (serverToken3_2.getCode() != 200) {
            return RestResponse.fail(503, "计算失败！");
        }
        jsonObject.put("分级矢量化", resultLayerName7);

        //黄土高原模型只有4级高危险缓冲区
        String gridvalue = "4";
        //ypg指定栅格矢量化缓冲区
        String resultLayerName_8 = "temp_黄土高原_矢量化" + gridvalue + "_" + currTime + "_" + dzIntensity;
        String resultLayerName_9 = "temp_黄土高原_缓冲区" + gridvalue + "_" + currTime + "_" + dzIntensity;
        Map<String, Object> map7 = new HashMap<>();
        map7.put("type", "countTifValueBuffer");
//        map7.put("layerName", resultLayerName3_1);//栅格分级计算
        map7.put("layerName", resultLayerName7);//栅格分级计算矢量化任务区域内
        map7.put("resultLayerName", resultLayerName_8);
        map7.put("resultLayerName2", resultLayerName_9);
        map7.put("gridvalue", gridvalue);
        map7.put("bufferMeter", roadRange);
        RestResponse serverToken4 = hypergraphService.getServerToken(map7);
        if (serverToken4.getCode() == 200) {
            //ypg矢量求交--任务区域内
            String resultLayerName9 = "ypg逻辑斯蒂模型_缓冲区"+gridvalue+"_" + currTime + "_" + dzIntensity;
            Map<String, Object> map7_1 = new HashMap<>();
            map7_1.put("type", "ypgIntersects");
            map7_1.put("layerName", resultLayerName_9);
            map7_1.put("clipLayerName", clipLayerName);
            map7_1.put("resultLayerName", resultLayerName9);
            RestResponse serverToken4_1 = hypergraphService.getServerToken(map7_1);
            if (serverToken4_1.getCode() == 200) {
                //ypg计算数据自动制图发布图层模板
                Map<String, Object> map7_2 = new HashMap<>();
                map7_2.put("type", "ypgMapsLayer");
                map7_2.put("layerName", resultLayerName9);
                map7_2.put("mapsName", "震后交通情况分布图_缓冲区图层模板.xml");
                RestResponse serverToken4_2 = hypergraphService.getServerToken(map7_2);
                if (serverToken4_2.getCode() == 200) {
                    //ypgTifCount复制数据集到fxfzypg
                    Map<String, Object> map7_3 = new HashMap<>();
                    map7_3.put("type", "ypgCountCopyVector");
                    map7_3.put("layerName", resultLayerName9);
                    RestResponse serverToken4_3 = hypergraphService.getServerToken(map7_3);
                    if (serverToken4_3.getCode() == 200) {
                        jsonObject.put("缓冲区4级", resultLayerName9);
                    }
                }
            }
        }

        return RestResponse.succeed(jsonObject);
    }

    public RestResponse getDataBySlopeVersion3(String geom, String version, Map<String, Object> map1) {
        String currTime = System.currentTimeMillis() + "";
        String tab = (String) map1.get("tab");
        String taskDistrict = (String) map1.get("taskDistrict");//任务区域
        List<String> isHave = new ArrayList<>();//防止收集的坡度文件名重复
        String layerNames = "";
        //遍历每一个区域
        for (String s1 : taskDistrict.split("、")) {
            if (s1 != null) {
                String[] s2 = s1.split("-");
                Map<String, QhMapFilesEntity> entityMap = new HashMap<>();
                //获取到这个省的所有坡度数据
                List<QhMapFilesEntity> qhMapFilesEntitys = qhMapFilesService.getSlopeFileByDivisionAndType(s2[0], null, null, "地形地貌（坡度）_");
                if (qhMapFilesEntitys != null && qhMapFilesEntitys.size() > 0) {
                    for (QhMapFilesEntity qhMapFilesEntity : qhMapFilesEntitys) {
                        if (PlatformObjectUtils.isNotEmpty(qhMapFilesEntity.getProvince())) {
                            if (PlatformObjectUtils.isNotEmpty(qhMapFilesEntity.getCity())) {
                                if (PlatformObjectUtils.isNotEmpty(qhMapFilesEntity.getArea())) {
                                    if ("北京市".equals(qhMapFilesEntity.getProvince()) || "天津市".equals(qhMapFilesEntity.getProvince())
                                            || "重庆市".equals(qhMapFilesEntity.getProvince()) || "上海市".equals(qhMapFilesEntity.getProvince())) {
                                        entityMap.put(qhMapFilesEntity.getProvince() + "-" + qhMapFilesEntity.getArea(), qhMapFilesEntity);
                                    } else {
                                        entityMap.put(qhMapFilesEntity.getProvince() + "-" + qhMapFilesEntity.getCity() + "-" + qhMapFilesEntity.getArea(), qhMapFilesEntity);
                                    }
                                } else {
                                    entityMap.put(qhMapFilesEntity.getProvince() + "-" + qhMapFilesEntity.getCity(), qhMapFilesEntity);
                                }
                            } else {
                                entityMap.put(qhMapFilesEntity.getProvince(), qhMapFilesEntity);
                            }
                        }
                    }
                }
                if (s2.length == 1) {
                    //省级
                    if (entityMap.containsKey(s1)) {
                        layerNames = entityMap.get(s1).getAffiliatedFileName();
                    } else {
                        for (Map.Entry<String, QhMapFilesEntity> entry : entityMap.entrySet()) {
                            String key = entry.getKey();
                            if (key.substring(0, key.indexOf("-")).equals(s1)) {
                                layerNames = layerNames + "-" + entry.getValue().getAffiliatedFileName();
                            }
                        }
                    }
                } else if (s2.length == 2) {
                    //市级
                    if (entityMap.containsKey(s1)) {
                        layerNames = entityMap.get(s1).getAffiliatedFileName();
                    } else if (entityMap.containsKey(s1.substring(0, s1.indexOf("-")))) {
                        layerNames = entityMap.get(s1.substring(0, s1.indexOf("-"))).getAffiliatedFileName();
                    } else {
                        for (Map.Entry<String, QhMapFilesEntity> entry : entityMap.entrySet()) {
                            String key = entry.getKey();
                            if (key.substring(0, key.lastIndexOf("-")).equals(s1)) {
                                layerNames = layerNames + "-" + entry.getValue().getAffiliatedFileName();
                            }
                        }
                    }
                } else {
                    //县级
                    if (entityMap.containsKey(s1)) {
                        layerNames = entityMap.get(s1).getAffiliatedFileName();
                    } else if (entityMap.containsKey(s1.substring(0, s1.lastIndexOf("-")))) {
                        layerNames = entityMap.get(s1.substring(0, s1.lastIndexOf("-"))).getAffiliatedFileName();
                    } else if (entityMap.containsKey(s1.substring(0, s1.indexOf("-")))) {
                        layerNames = entityMap.get(s1.substring(0, s1.indexOf("-"))).getAffiliatedFileName();
                    }
                }
            }
        }
        if ("".equals(layerNames)) {
            return RestResponse.fail(503, "未获取到该任务地区的坡度文件！");
        }
        String countString = "";
        if (layerNames.indexOf("-") == 0) {
            layerNames = layerNames.substring(1);
        }
        if (!layerNames.contains("-")) {
            countString = "Con([demtif." + layerNames + "]==-9999,-9999,[demtif." + layerNames + "]),";
        } else {
            String countString1 = "", countString2 = "", countString3 = "";
            String[] layerNameArr = layerNames.split("-");
            for (int i = layerNameArr.length - 1; i >= 0; i--) { //3 2 1 0
                countString1 = "Con([demtif." + layerNameArr[i] + "]==-9999,";
                if (i == layerNameArr.length - 1) {
                    countString2 = "-9999,";
                } else {
                    countString2 = countString;
                }
                countString3 = "[demtif." + layerNameArr[i] + "]),";
                countString = countString1 + countString2 + countString3;
            }
        }
        Map<String, Object> map3 = new HashMap<>();
        map3.put("type", "ypgCountTif");
        String resultLayerName3 = "temp_ypg逻辑斯蒂模型坡度_" + currTime;
        map3.put("layerName", resultLayerName3);
        map3.put("countString", countString.substring(0, countString.length() - 1));
        RestResponse serverToken = hypergraphService.getServerToken(map3);
        if (serverToken.getCode() != 200) {
            return RestResponse.fail(503, "该任务地区的坡度文件发布超图失败！");
        }

        return count3Detail(resultLayerName3, currTime, map1);
    }

    public RestResponse getDataBySlopeVersion4(String geom, String version, Map<String, Object> map1) {
        String layerName = "";
        String resultLayerName1 = "";
//        String currTime = System.currentTimeMillis() + "";
        String currTime = (String) map1.get("currTime");
        String url = basicDataUrl2 + "/sysDataVersion/getFilePathByVersion?versionCode=" + version;
        RestResponse jcsjPage = getJCSJ(url, 2);
        JSONObject jsonObject = (JSONObject) jcsjPage.getData();
        String filePath = jsonObject.getString("filePath");
        String[] split = filePath.split("\\\\");
        String[] split1 = split[split.length - 1].split("/");
        layerName = split1[split1.length - 1].split("\\.")[0];
        if (layerName.contains(".tif")) {
            layerName = layerName.replace(".tif", "");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("type", "clipTif2-dzzhTifFile");//dzzh系统坡度文件
        map.put("layerName", layerName);
//        resultLayerName1 = layerName + "_裁剪_" + currTime;//裁剪结果数据集
        resultLayerName1 = "temp_dzzh坡度裁剪_" + currTime;//裁剪结果数据集
        map.put("resultLayerName", resultLayerName1);
        map.put("geomText", geom);
        RestResponse serverToken = hypergraphService.getServerToken(map);
        if (serverToken.getCode() != 200) {
            return RestResponse.fail(503, "文件获取失败！");
        }
        return count4Detail(resultLayerName1, map1, currTime);
    }

    /**
     * @param type          vectorTif-3//ypg边界裁剪dzzh  vectorTif-4//ypg边界裁剪基础数据 vectorTif-5//ypg边界裁剪ypg
     * @param layerName     矢量转栅格的数据集
     * @param clipLayerName 边界数据集
     * @param fieldName     用于生成栅格值的矢量数据的字段，默认用超图自身的字段SmUserID值为0
     * @param sqlFilter     过滤查询数据的表达式，即只保留不符合sql条件的数据
     * @param sqlFilterClip 边界过滤查询数据的表达式，即只保留符合sql条件的数据
     * @param currTime 时间戳
     * @return
     */
    private RestResponse vectorTif(String type, String layerName, String clipLayerName, String fieldName,
                                   String sqlFilter, String sqlFilterClip, String currTime) {
        Map<String, Object> map7 = new HashMap<>();
        map7.put("type", type);
        map7.put("layerName", layerName);//矢量转栅格的数据集
        map7.put("clipLayerName", clipLayerName);//边界数据集
        map7.put("fieldName", fieldName);//用于生成栅格值的矢量数据的字段，默认用超图自身的字段SmUserID值为0
        //过滤查询数据的表达式，即只保留不符合sql条件的数据
        map7.put("sqlFilter", sqlFilter);
        //边界过滤查询数据的表达式，即只保留符合sql条件的数据
        map7.put("sqlFilterClip", sqlFilterClip);
        map7.put("currTime", currTime);
        return hypergraphService.getServerToken(map7);
    }

    /**
     * @param type            countTif:栅格计算发布;countTif2:栅格计算;ypgCountTif-1:栅格计算ypg
     * @param countString
     * @param resultLayerName
     * @return
     */
    private RestResponse countTif(String type, String countString, String resultLayerName) {
        //栅格计算
        Map<String, Object> map2_1 = new HashMap<>();
        map2_1.put("type", type);
        map2_1.put("layerName", resultLayerName);
        map2_1.put("countString", countString);
        return hypergraphService.getServerToken(map2_1);
    }


    @Override
    public RestResponse getParam0Version(Map<String, Object> map) {
        String url = basicDataUrl2 + "/sysDataVersion/getYwVesrionData?userId=" + PlatformSessionUtils.getUserId();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null) {
                url = url + "&" + entry.getKey() + "=" + entry.getValue();
            }
        }
        RestResponse jcsjPage = getJCSJ(url, 2);
        return jcsjPage;
    }

    private RestResponse getJCSJ(String url, int tab) {
        MultiValueMap<String, Object> valueMap = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "fxfzdzzh");
        headers.set("subsystemCode", "dzdzzhpg");
        HttpEntity<MultiValueMap> r = new HttpEntity<>(valueMap, headers);
        RestResponse resp = null;
        try {
            if (tab == 1) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 2) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 3) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONArray("data");
                resp = RestResponse.succeed(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }

    @Override
    public RestResponse getTrafficAnalysisByTaskId(String taskId,String dzIntensity) {
        return RestResponse.succeed(countLandslideRepository.getTrafficAnalysisByTaskId(taskId,dzIntensity));
    }

    @Override
    public RestResponse saveTrafficAnalysis(TrafficAnalysis entity) {
        entity.setUuid(UUIDGenerator.getUUID());
        String userId = PlatformSessionContext.getUserID();
        entity.setCreateUserId(userId);
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        entity.setCreateUser(sUser.getUserName());
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setIsDelete(YNEnum.N.toString());
        countLandslideRepository.saveTrafficAnalysis(entity);
        return ResponseCreator.createSuccessResponse(entity, "保存成功！");
    }

    @Override
    public RestResponse updateTrafficAnalysis(TrafficAnalysis entity) {
        TrafficAnalysis trafficAnalysisByTaskId = countLandslideRepository.getTrafficAnalysisByTaskId(entity.getTaskId(),entity.getDzIntensity());
        UpdateUtil.copyNullProperties(trafficAnalysisByTaskId, entity);
        entity.setUpdateUser(PlatformSessionUtils.getUserId());
        entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        countLandslideRepository.updateTrafficAnalysis(entity);
        return ResponseCreator.createSuccessResponse(entity, "修改成功！");
    }

    @Override
    public String getSlopeModelIntensity(String taskId) {
        String intensity = countLandslideRepository.getSlopeModelIntensity(taskId);
        return intensity;
    }
}
